package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @author: liyuan
 * @data 2020-11-23 15:57
 */
@Configuration
public class WxAddMediaTypeRestTemplate {
    /***
     * 覆盖原来的RestTemplate对象
     * @return
     * 使用debug看第8个含有变化；或者使用工厂模式
     */
    @Bean
    public RestTemplate wxMediaType() {
        RestTemplate restTemplate = new RestTemplate();
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        messageConverters.add(new WxMappingJackson2HttpMessageConverter());
        List<List<MediaType>> collect = messageConverters.stream().map(HttpMessageConverter::getSupportedMediaTypes).collect(Collectors.toList());
        return restTemplate;
    }

    /***
     * 添加能转换的类型
     */
    private static class WxMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
        public WxMappingJackson2HttpMessageConverter() {
            List<MediaType> mediaTypes = new ArrayList<>();
            mediaTypes.add(MediaType.TEXT_PLAIN);//plain类型
            mediaTypes.add(MediaType.TEXT_HTML);//html类型
            setSupportedMediaTypes(mediaTypes);//
        }
    }
}
